﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;

namespace RenShiPinYongBiao
{
    public partial class MainForm : Form
    {
        private TablePrinter tp;
        public MainForm()
        {
            InitializeComponent();
            
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            Application.Exit();
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Multiselect = false;
            ofd.Filter = "Excel2003文件(*.xls)|*.xls";
            ofd.ShowDialog();
            if (!File.Exists(ofd.FileName))
            {
                return;
            }
            this.Enabled = false;
            this.UseWaitCursor = true;
            try
            {
                ExcelReader reader = new ExcelReader(ofd.FileName);
                DataSet ds = reader.GetData();
                ConnectionManager.OpenConnection();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    string id = dr["职工号"].ToString();
                    SqlCommand cm = ConnectionManager.Connection.CreateCommand();
                    cm.CommandText = "select * from THouseHold where FEmployeeID=@id and FName=@name";
                    cm.Parameters.AddWithValue("id", id);
                    cm.Parameters.AddWithValue("name", dr["姓名"]);
                    if (cm.ExecuteScalar() != null)
                    {
                        cm.CommandText = "update THouseHold set FRelation=@relation,FName=@name,FBirthday=@birthday,FParty=@party,FCompany=@company,FHeadShip=@headship,FGender=@gender where FEmployeeID=@id and FName=@name";
                    }
                    else
                    {
                        cm.CommandText = "insert into THouseHold (FEmployeeID,FRelation,FName,FBirthday,FParty,FCompany,FHeadShip,FOperateDate,FUserID,FGender) values (@id,@relation,@name,@birthday,@party,@company,@headship,@operateDate,@user,@gender)";
                        cm.Parameters.AddWithValue("operateDate", DateTime.Now);
                        cm.Parameters.AddWithValue("user", OperatorControl.FUserID);
                    }
                    //cm.Parameters.AddWithValue("id", id);
                    cm.Parameters.AddWithValue("relation", dr["关系"]);
                    //cm.Parameters.AddWithValue("name", dr["姓名"]);
                    cm.Parameters.AddWithValue("birthday", dr["出生日期"]);
                    cm.Parameters.AddWithValue("company", dr["工作单位"]);
                    cm.Parameters.AddWithValue("headship", dr["职务"]);
                    cm.Parameters.AddWithValue("party", dr["政治面貌"]);
                    //cm.Parameters.AddWithValue("gender", dr["性别"]);
                    cm.Parameters.AddWithValue("gender", "无");
                    //try
                    //{
                    //}
                    //catch (System.Exception ex)
                    //{
                    //    //if (ex.Message.Contains("FK_THouseHold_TEmployee"))
                    //    //{
                            
                    //    //}
                    //}
                    cm.ExecuteNonQuery();
                }
                ConnectionManager.CloseConnection();
            }
            catch (Exception ex)
            {
                MessageBox.Show("导入数据失败："+ex.Message +"请检查数据文件和网络连接");
                ConnectionManager.CloseConnection();
            }
            this.Enabled = true;
            this.UseWaitCursor = false;
            MessageBox.Show("导入数据完成");
        }

        

        private void MainForm_Load(object sender, EventArgs e)
        {
            // TODO: 这行代码将数据加载到表“hrdbDataSet1.TDictBelongOrgan”中。您可以根据需要移动或删除它。
            this.tDictBelongOrganTableAdapter.Fill(this.hrdbDataSet1.TDictBelongOrgan);
            // TODO: 这行代码将数据加载到表“hrdbDataSet1.TEmployee”中。您可以根据需要移动或删除它。
            this.tDictPartyTableAdapter.Fill(this.hrdbDataSet1.TDictParty);
            // TODO: 这行代码将数据加载到表“hrdbDataSet1.TDictNation”中。您可以根据需要移动或删除它。
            this.tDictNationTableAdapter.Fill(this.hrdbDataSet1.TDictNation);
            // TODO: 这行代码将数据加载到表“hrdbDataSet1.TDictGender”中。您可以根据需要移动或删除它。
            this.tDictGenderTableAdapter.Fill(this.hrdbDataSet1.TDictGender);
            //this.tEmployeeTableAdapter.FillByName(this.hrdbDataSet1.TEmployee, "孙慧");
        }

        private void dataGridView1_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {

        }

        private void pdocRegTable_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            tp.Print(e);
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            DialogResult result = printDialog.ShowDialog();
            pdocRegTable.PrinterSettings = printDialog.PrinterSettings;
            if (result == DialogResult.OK)
            {
                pdocRegTable.Print();
            }
        }

        private void btnPrintPreview_Click(object sender, EventArgs e)
        {
            //printPreviewDialog.DesktopLocation=new Point(0,0);
            //printPreviewDialog.Width = 827;
            //printPreviewDialog.Height = 1169;
            //printPreviewDialog.PrintPreviewControl.Zoom = 1;
            //printPreviewDialog.PrintPreviewControl.Width = 800;
            //printPreviewDialog.PrintPreviewControl.Height = 1100;
            printPreviewDialog.ShowDialog();
        }

        private void pdocRegTable_BeginPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
        {
            this.tp = new TablePrinter(this.getPrintTable());
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            this.hrdbDataSet1.TEmployee.Clear();
            this.Enabled = false;
            this.UseWaitCursor = true;
            if (!this.cbName.Text.Equals(""))
            {
                this.tEmployeeTableAdapter.FillByName(this.hrdbDataSet1.TEmployee, cbName.Text);
            }
            else
            {
                if (this.checkBoxbOrganUse.Checked)
                {
                    this.tEmployeeTableAdapter.FillByConditionRegularAndOrgan(this.hrdbDataSet1.TEmployee, dtpStart.Value, dtpEnd.Value, cbType.SelectedValue.ToString());
                }
                else
                {
                    this.tEmployeeTableAdapter.FillByConditionRegular(this.hrdbDataSet1.TEmployee, dtpStart.Value, dtpEnd.Value);
                }
            }
            
            this.Enabled = true;
            this.UseWaitCursor = false;
            tbsName.Focus();
            tbsName.SelectAll();
        }
        private DataTable getPrintTable()
        {
            DataTable d = null;
            if (!chkbExportAll.Checked)
            {
                d = hrdbDataSet1.TEmployee.Clone();
                for (int i = 0; i < dataGridView1.SelectedRows.Count; i++)
                {
                    int k = dataGridView1.SelectedRows[i].Index;
                    DataRow r = d.NewRow();
                    r.ItemArray = (object[])hrdbDataSet1.TEmployee.Rows[k].ItemArray.Clone();
                    d.Rows.Add(r);
                }
            }
            else
            {
                d = hrdbDataSet1.TEmployee;
            }
            return d; 
        }
        private void btnExport_Click(object sender, EventArgs e)
        {
            

            SaveFileDialog sfd = new SaveFileDialog();
            sfd.AddExtension = true;
            sfd.DefaultExt = "doc";
            sfd.Filter = "Word2003文件(*.doc)|*.doc";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                this.Enabled = false;
                this.UseWaitCursor = true;
                WordExporter exp = new WordExporter(this.getPrintTable());
                exp.Export(sfd.FileName);
                this.UseWaitCursor = false;
                this.Enabled = true;
                MessageBox.Show("文件导出结束");
            }
        }

        private void tbsName_KeyUp(object sender, KeyEventArgs e)
        {
            this.tEmployeeCodeDictTableAdapter.FillByInputCode(this.hrdbDataSet1.TEmployeeCodeDict, tbsName.Text);

            
        }

        private void tbsName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                cbName.Focus();
            }
        }

        private void cbName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnSearch.Focus();
            }
        }

        private void btnImportNationParty_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Multiselect = false;
            ofd.Filter = "Excel2003文件(*.xls)|*.xls";
            ofd.ShowDialog();
            if (!File.Exists(ofd.FileName))
            {
                return;
            }
            this.Enabled = false;
            try
            {
                ExcelReader er = new ExcelReader(ofd.FileName);
                DataSet ds = er.GetData();
                ConnectionManager.OpenConnection();
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    string id = row["档案号"].ToString();
                    SqlCommand cmd = ConnectionManager.Connection.CreateCommand();
                    cmd.CommandText = "update TEmployee set FNationCode=@ncode,FPartyCode=@pcode where FEmployeeID=@id";
                    cmd.Parameters.AddWithValue("id", id);
                    cmd.Parameters.AddWithValue("ncode", DataSourcePinYong.FindCodeByName(row["民族"], this.hrdbDataSet1.TDictNation));
                    cmd.Parameters.AddWithValue("pcode", DataSourcePinYong.FindCodeByName(row["政治面貌"], this.hrdbDataSet1.TDictParty));
                    cmd.ExecuteNonQuery();
                }
                ConnectionManager.CloseConnection();
            }
            catch (Exception ex)
            {
                MessageBox.Show("导入数据失败：" + ex.Message + "请检查数据文件和网络连接");
                ConnectionManager.CloseConnection();
            }
            this.Enabled = true;
            MessageBox.Show("数据导入结束");
        }

        private void btnImportIntoHisDate_Click(object sender, EventArgs e)
        {
            //OpenFileDialog ofd = new OpenFileDialog();
            //ofd.Multiselect = false;
            //ofd.Filter = "Excel2003文件(*.xls)|*.xls";
            //ofd.ShowDialog();
            //if (!File.Exists(ofd.FileName))
            //{
            //    return;
            //}
            //this.Enabled = false;
            //try
            //{
            //    ExcelReader er = new ExcelReader(ofd.FileName);
            //    DataSet ds = er.GetData();
            //    ConnectionManager.OpenConnection();
            //    foreach (DataRow row in ds.Tables[0].Rows)
            //    {
            //        string id = row["档案号"].ToString();
            //        SqlCommand cmd = ConnectionManager.Connection.CreateCommand();
            //        cmd.CommandText = "update TEmployee set FIntoHisDate=@hisDate where FEmployeeID=@id";
            //        cmd.Parameters.AddWithValue("id", id);
            //        cmd.Parameters.AddWithValue("hisDate", row["入院时间"]);
            //        cmd.ExecuteNonQuery();
            //    }
            //    ConnectionManager.CloseConnection();
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show("导入数据失败：" + ex.Message + "请检查数据文件和网络连接");
            //    ConnectionManager.CloseConnection();
            //}
            //this.Enabled = true;
            //MessageBox.Show("数据导入结束");
        }

        private void btnExportTechTable_Click(object sender, EventArgs e)
        {
            WordExporterTemplate wet = new WordExporterTemplate(Environment.CurrentDirectory + "\\TechTemplate.dot");
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Multiselect = false;
            ofd.Filter = "Excel2003文件(*.xls)|*.xls";
            ofd.ShowDialog();
            if (!File.Exists(ofd.FileName))
            {
                return;
            }
            this.Enabled = false;
            //try
            //{
                ExcelReader er = new ExcelReader(ofd.FileName);
                DataSet ds = er.GetData();
                wet.Export(ds.Tables[0]);
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show("导入数据失败：" + ex.Message);
            //}
            this.Enabled = true;
            MessageBox.Show("导出文件结束");
        }
    }
}
